package com.guang.springbootselfmvc.config;

import com.guang.springbootselfmvc.properties.Swagger3Properties;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableConfigurationProperties({Swagger3Properties.class})
public class Swagger3Config implements WebMvcConfigurer {
    public Swagger3Config() {
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(new String[]{"/swagger-ui/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/springfox-swagger-ui/"}).resourceChain(false);
    }

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/swagger-ui/").setViewName("forward:/swagger-ui/index.html");
    }

    @Bean
    public Docket createRestApi(Swagger3Properties swagger3Properties) {
        return (new Docket(DocumentationType.OAS_30)).apiInfo(this.apiInfo(swagger3Properties)).enable(swagger3Properties.isEnable()).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(Swagger3Properties swagger3Properties) {
        return (new ApiInfoBuilder()).title(swagger3Properties.getTitle()).description(swagger3Properties.getDescription()).contact(new Contact(swagger3Properties.getManagerName(), swagger3Properties.getManagerPageUrl(), swagger3Properties.getManagerEmail())).version(swagger3Properties.getDescriptionNo()).build();
    }
}